from django.core.cache import cache
import re
from rest_framework.authentication import BaseAuthentication

from cost.models import User
from utils.errors import ParamsException


class MyUserAuthentication(BaseAuthentication):

    def authenticate(self, request):
        urls = request.path
        if urls in ['/cost/user/login/', '/cost/user/register/', '/static/upload/[.]+', '/cost/check_code/',
                    '/cost/get_version_info/', '/cost/get_tel_code/', '/cost/user/find_my_password/',
                    '/cost/show_weather/', '/cost/get_code_img/']:
            return None

        token = request.query_params.get('token')
        if not token:
            raise ParamsException({'code': '4001', 'message': '无法访问'})
        user_id = cache.get(token)
        if not user_id:
            raise ParamsException({'code': '4002', 'message': '无法访问'})
        user = User.objects.get(pk=user_id)
        # 验证管理员操作的接口
        if user.user_type != 9 and (urls in ['/cost/user/', ] or re.fullmatch(r'/cost/user/[0-9]+/', urls)):
            raise ParamsException({'code': '4003', 'message': '无法访问'})
        return user, token
